from datetime import datetime

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet

from apps.Cat.models import varieties, CatModels
from apps.Cat.serializers import varietiesSerializer, CatModelsSerializer


class varietiesViewSet(ModelViewSet):
    queryset = varieties.objects.order_by('pk')
    serializer_class = varietiesSerializer


class CatModelsViewSet(ModelViewSet):
    queryset = CatModels.objects.order_by('pk')
    serializer_class = CatModelsSerializer
    filter_backends = [DjangoFilterBackend]  # 应用筛选器
    filter_fields = {"Cat_state": ["exact"]}  # 可以通过这个来选择出当前已经出售和未出售的猫
    """
    也可以使用别的方法进行刷选，使用 django_filters 的意图在于高扩展性和简单使用
    - 筛选出未出售的猫的信息
    CatModels.objects.filter(Cat_state="NotState") 
    - 筛选出已经出售的猫的信息
    CatModels.objects.filter(Cat_state="YesState") 
    """

    @action(methods=['get'], detail=False)
    def srevenue(self, request):
        sd = request.query_params.get("sd")
        ed = request.query_params.get("ed")
        print(type(sd),type(ed), sd, ed)
        if all([ed, sd]):
            sum = 0
            cats = CatModels.objects.filter(Cat_transaction_time__range=(sd,ed))
            for i in cats:
                sum += i.Cat_Price
        else:
            sum = 0
        return response.Response(sum)
